package com.example.reactor;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class ReactorServer {

    private static final Logger log = LoggerFactory.getLogger(ReactorServer.class);


    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8080));
        Selector selector = Selector.open();
        serverSocketChannel.configureBlocking(false); // 设置为非阻塞
        // 注册 关注链接事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        Worker worker = new Worker("worker1");
        while (true) {
            log.info("开始监听连接");
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                // 移除
                iterator.remove();
                if (selectionKey.isAcceptable()) {
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    log.info("监听到连接:{}", socketChannel);
                    worker.register(socketChannel);
                }
            }
        }

    }
}
